﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Bll;
using System.Collections.ObjectModel;
using CSP.Bll.IObjectBlls;
using CSP.Model.CSP;
using CSP.Model.CSPEnum;

namespace CSP.Web.MyHome.ServiceInfo
{
    public partial class Modify : CSPMyHome
    {
        private string _currentURL = "";

        private bool _isPriceRange = false;

        /// <summary>
        /// 当前的url路径
        /// </summary>
        protected string CurrentURL
        {
            get
            {
                return _currentURL;
            }
        }

        /// <summary>
        /// 价格类型
        /// </summary>
        protected bool IsPriceRange
        {
            get 
            {
                return _isPriceRange;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            _currentURL = Server.UrlEncode(Request.Url.OriginalString);
            if(!IsPostBack)
            {
                InitControl();
            }
        }

        private void InitControl()
        {
            BindAddressUI();
            BindOriginalPriceUnitUI();
            BindPriceUnitUI();
            BindClassTypeUI();
            BindServiceInfoUI();
            //Dictionary<int, string> imageUrls = new Dictionary<int, string>();
            //imageUrls.Add(1, "/Upload/Tmp/image/20120906/201296009734.jpg");
            //imageUrls.Add(2, "/Upload/Tmp/image/20120906/201296009734.jpg");
            //this.U_ImageUpload.SetImageURL = imageUrls;
        }



        private void BindAddressUI()
        {
            this.R_Address.DataSource = GetServiceAreaByUser();
            this.R_Address.DataTextField = "name";
            this.R_Address.DataValueField = "id";
            this.R_Address.DataBind();
            if (this.R_Address.Items.Count != 0)
            {
                this.R_Address.Items[0].Selected = true;
            }
        }

        private void BindOriginalPriceUnitUI()
        {
            this.S_OriginalPriceUnit.DataSource = GetPriceUnit();
            this.S_OriginalPriceUnit.DataTextField = "name";
            this.S_OriginalPriceUnit.DataValueField = "id";
            this.S_OriginalPriceUnit.DataBind();
        }

        private void BindPriceUnitUI()
        {
            this.S_PriceUnit.DataSource = GetPriceUnit();
            this.S_PriceUnit.DataTextField = "name";
            this.S_PriceUnit.DataValueField = "id";
            this.S_PriceUnit.DataBind();
        }

        private void BindClassTypeUI()
        {
            this.S_ClassType.DataSource = GetClassType();
            this.S_ClassType.DataTextField = "name";
            this.S_ClassType.DataValueField = "id";
            this.S_ClassType.DataBind();
        }

        private void BindServiceInfoUI()
        {
            //控件中图片发布
            CSP.Model.CSP.ServiceInfo serviceInfo = GetServiceInfoById(Convert.ToInt32(Request["id"].ToString()));

            //serviceInfo.username = UserProvider.UserName;
            Txt_Title.Value = serviceInfo.title;
            Txt_Description.Value = serviceInfo.Description;
            Txt_ServiceType.Value = serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceTypeId.ToString();


            //ServiceTypeId = Convert.ToInt32(this.Server.UrlDecode(Request["InfoType"]).Split(',')[2].Split('|')[1]),
            ListItem priceTypeItem = S_PriceType.Items.FindByValue(serviceInfo.PriceType.ToString());
            if(priceTypeItem!=null)
            {
                priceTypeItem.Selected = true;
                if ((PriceType)serviceInfo.PriceType == PriceType.PriceRange)
                {
                    _isPriceRange = true;
                }
            }
            Txt_PriceStart.Value=serviceInfo.PriceStart.ToString("0.00");
            Txt_PriceEnd.Value = serviceInfo.PriceEnd.ToString("0.00");
            Txt_Price.Value = serviceInfo.Price.ToString("0.00");
            ListItem priceUnitItem=S_PriceUnit.Items.FindByValue(serviceInfo.PriceUnitId.ToString());
            if (priceUnitItem!=null)
            {
                priceUnitItem.Selected = true;
            }

            Txt_OriginalPrice.Value = serviceInfo.OriginalPrice != null ? serviceInfo.OriginalPrice.Value.ToString("0.00") : "0";
            S_OriginalPriceUnit.Items.FindByValue(serviceInfo.OriginalPriceUnitld.ToString()).Selected = true;
            ListItem addressItem=this.R_Address.Items.FindByValue(serviceInfo.ServiceInfoAddressRels.ToArray()[0].AddressId.ToString());
            if (addressItem != null)
            {
                addressItem.Selected = true;
            }

            //AddressId = Convert.ToInt32(this.R_Address.SelectedValue),
            Txt_ClassOfMemberNumber.Value = serviceInfo.ClassOfMemberNumber.ToString();
            AgeStart.Items.FindByValue(serviceInfo.AgeStart.ToString()).Selected = true; //.ToString("yyyy-MM-dd");
            AgeEnd.Items.FindByValue(serviceInfo.AgeEnd.ToString()).Selected = true;
            S_ClassType.Items.FindByValue(serviceInfo.ClassTypeId.ToString()).Selected = true;
            Txt_ClassValidityStart.Text = serviceInfo.ClassValidityStart.ToString("yyyy-MM-dd");
            Txt_ClassValidityEnd.Text = serviceInfo.ClassValidityEnd.ToString("yyyy-MM-dd");
            Txt_EnjoyCount.Value = serviceInfo.EnjoyCount.ToString();
            Txt_KeyWords.Value = serviceInfo.KeyWords;
            U_CSPEditor.Text = serviceInfo.Content;
            //serviceInfo.img = U_CSPEditor.ImageURL;
            R_Status.SelectedValue = serviceInfo.status.ToString();
            SetCSP_UploadImages(serviceInfo.ServiceImages);
            Txt_OnLineTime.Value = serviceInfo.OnLineTime != null ? serviceInfo.OnLineTime.Value.ToString("yyyy-MM-dd hh:mm:ss") : "";

            this.L_ServiceType.InnerText = serviceInfo.ServiceInfoServiceTypeRels.ToArray()[0].ServiceType.Name;
        }

        /// <summary>
        /// 根据UI获取需要添加的ServiceInfo
        /// </summary>
        /// <returns></returns>
        private CSP.Model.CSP.ServiceInfo GetModifiedServiceInfoByUI()
        {
            //控件中图片发布
            this.U_ImageUpload.ReleaseImg();
            this.U_CSPEditor.ReleaseImg();
            CSP.Model.CSP.ServiceInfo serviceInfo = GetServiceInfoById(Convert.ToInt32(Request["id"].ToString()));
            CSP.Model.CSP.ServiceInfo result = new Model.CSP.ServiceInfo();
            result.id = serviceInfo.id;
            result.username = UserProvider.UserName;
            result.img = serviceInfo.img;
            result.title = Txt_Title.Value;
            result.Description = Txt_Description.Value;
            result.ServiceInfoServiceTypeRels = new ServiceInfoServiceTypeRel[] { new ServiceInfoServiceTypeRel { 
                ServiceTypeId=Convert.ToInt32(this.Txt_ServiceType.Value)
                } };
            //ServiceTypeId = Convert.ToInt32(this.Server.UrlDecode(Request["InfoType"]).Split(',')[2].Split('|')[1]),
            result.PriceType = Convert.ToInt32(this.S_PriceType.Value.Trim());
            result.PriceStart = Convert.ToDecimal(this.Txt_PriceStart.Value.Trim());
            result.PriceEnd = Convert.ToDecimal(this.Txt_PriceEnd.Value.Trim());
            result.Price = Convert.ToDecimal(Txt_Price.Value);
            result.PriceUnitId = Convert.ToInt32(S_PriceUnit.Value);
            result.OriginalPrice = Convert.ToDecimal(Txt_OriginalPrice.Value);
            result.OriginalPriceUnitld = Convert.ToInt32(S_OriginalPriceUnit.Value);
            result.ServiceInfoAddressRels = new ServiceInfoAddressRel[] { new ServiceInfoAddressRel { 
                    AddressId=Convert.ToInt32(this.R_Address.SelectedValue)
                } };
            //AddressId = Convert.ToInt32(this.R_Address.SelectedValue),
            result.ClassOfMemberNumber = Convert.ToInt32(Txt_ClassOfMemberNumber.Value);
            result.AgeStart = AgeStart.Value;
            result.AgeEnd = Convert.ToInt32(AgeEnd.Value);
            result.ClassTypeId = Convert.ToInt32(S_ClassType.Value);
            result.ClassValidityStart = Convert.ToDateTime(Txt_ClassValidityStart.Text);
            result.ClassValidityEnd = Convert.ToDateTime(Txt_ClassValidityEnd.Text);
            result.EnjoyCount = Convert.ToInt32(Txt_EnjoyCount.Value);
            result.KeyWords = Txt_KeyWords.Value;
            result.Content = U_CSPEditor.Text;
            result.img = U_CSPEditor.ImageURL;
            result.status = serviceInfo.status;
            result.LastModified = serviceInfo.LastModified;
            result.OnLineTime = serviceInfo.OnLineTime;
            result.ServiceImages = GetServiceImages(serviceInfo.ServiceImages.ToArray());
            if (this.Txt_OnLineTime.Value != "")
            {
                result.OnLineTime = Convert.ToDateTime(this.Txt_OnLineTime.Value);
            }
            else
            {
                result.OnLineTime = null;
            }
            result.CreateTime = DateTime.Now;


            return result;
        }


        private ServiceImage[] GetServiceImages(ServiceImage[] serviceImages)
        {
            serviceImages.Clone();
            List<ServiceImage> imgs = new List<ServiceImage>();
            int[] deleteIds = this.U_ImageUpload.DeleteImageIds;

            for (int i = 0; i < serviceImages.Length; i++)
            {
                ServiceImage serviceImage = new ServiceImage();
                serviceImage.Name = serviceImages[i].Name;
                serviceImage.OrderId = this.U_ImageUpload.GetOrderId(serviceImages[i].FilePath + "S_"+serviceImages[i].FileName);
                serviceImage.FileName = serviceImages[i].FileName;
                serviceImage.FilePath = serviceImages[i].FilePath;
                if (deleteIds.Contains(serviceImages[i].Id))
                {
                    serviceImage.ImageOperateSatus = Model.CSPEnum.ImageOperateSatus.Deleted;
                    serviceImage.Id = serviceImages[i].Id;
                }
                else
                {
                    serviceImage.ImageOperateSatus = Model.CSPEnum.ImageOperateSatus.Original;
                    serviceImage.Id = serviceImages[i].Id;
                }
                imgs.Add(serviceImage);
            }

            for (int i = 0; i < this.U_ImageUpload.NewImageURLs.Length; i++)
            {
                int index = this.U_ImageUpload.NewImageURLs[i].LastIndexOf("/");
                string path = this.U_ImageUpload.NewImageURLs[i].Substring(0, index + 1);
                string fileName = this.U_ImageUpload.NewImageURLs[i].Substring(index + 1);
                //this.U_ImageUpload.NewImageURLs=;
                imgs.Add(new ServiceImage
                {
                    Name = "",
                    FileName = fileName,
                    FilePath = path,
                    OrderId = this.U_ImageUpload.GetOrderId(path + fileName),
                    ImageOperateSatus = Model.CSPEnum.ImageOperateSatus.Added
                });
            }

            return imgs.ToArray();
        }

        private void SetCSP_UploadImages(ICollection<ServiceImage> serviceImages)
        {

            Dictionary<int, string> imges = new Dictionary<int, string>();
            if (serviceImages.Count == 0)
            {
                return;
            }
            serviceImages = serviceImages.OrderBy(i => i.OrderId).ToArray();
            foreach (var img in serviceImages)
            {
                imges.Add(img.Id, img.FilePath + "S_"+img.FileName);
            }
            this.U_ImageUpload.SetImageURL = imges;
        }

        /// <summary>
        /// 根据当前用户获取地理位置
        /// </summary>
        private ICollection<CSP.Model.CSP.Address> GetServiceAreaByUser()
        {
            ICollection<CSP.Model.CSP.Address> addresses = new Collection<CSP.Model.CSP.Address>();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IAddressBll addressBll = bllFactory.GetAddressBll())
            {
                addresses = addressBll.FindByUser(UserProvider.UserName);
            }
            return addresses;
        }

        /// <summary>
        /// 获取价格单位
        /// </summary>
        /// <returns></returns>
        private ICollection<PriceUnit> GetPriceUnit()
        {
            ICollection<PriceUnit> priceUnits = new Collection<PriceUnit>();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IPriceUnitBll priceUnitBll = bllFactory.GetPriceUnitBll())
            {
                priceUnits = priceUnitBll.FindAll();
            }
            return priceUnits;
        }

        /// <summary>
        /// 获取开课方式
        /// </summary>
        /// <returns></returns>
        private ICollection<ClassType> GetClassType()
        {
            ICollection<ClassType> classTypes = new Collection<ClassType>();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IClassTypeBll classTypeBll = bllFactory.GetClassTypeBll())
            {
                classTypes = classTypeBll.FindAll();
            }
            return classTypes;
        }

        private CSP.Model.CSP.ServiceInfo GetServiceInfoById(int id)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            CSP.Model.CSP.ServiceInfo result = null;
            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                result = serviceInfoBll.GetByIdAndUser(id, UserProvider.UserName);
            }
            return result;
        }

        protected void Btn_Submit_Click(object sender, EventArgs e)
        {
            CSP.Model.CSP.ServiceInfo serviceInfo = GetModifiedServiceInfoByUI();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            ServiceImage[] serviceImages = serviceInfo.ServiceImages.ToArray();

            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                try
                {
                    serviceInfoBll.Update(serviceInfo);
                    U_ImageUpload.RemoveImages(serviceImages);
                }
                catch (Exception ex)
                {
                    LoggerProvider.Error(ex);
                    this.FailRedirect("提交未失败", "/MyHome/ServiceInfo/List.aspx");
                }
            }

            Response.Redirect("~/MyHome/ServiceInfo/PublishOK.aspx?id=" + serviceInfo.id.ToString());
        }

        
    }
}